package com.example.simpleprefencepratice;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    private static final int MODE = Context.MODE_PRIVATE;
    public static final String PREFERENCE_NAME = "QQSetting";
    SharedPreferences sp;
    SharedPreferences.Editor edit;
    EditText username;
    EditText password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sp = getSharedPreferences(PREFERENCE_NAME, MODE);
        edit = sp.edit();
        Button bt1 = (Button) findViewById(R.id.button);
        username = (EditText) findViewById(R.id.editTextTextPersonName);
        password = (EditText) findViewById(R.id.editTextTextPersonName1);
        CheckBox cb1 = (CheckBox) findViewById(R.id.checkBox);
        bt1.setOnClickListener((v) -> {
            boolean checked = cb1.isChecked();
            if (checked) {
                edit.putString("username", username.getText() == null ? "" : username.getText().toString());
                edit.putString("password", password.getText() == null ? "" : password.getText().toString());
                edit.commit();
            }
            Toast.makeText(this, "跳转界面", Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        String username = sp.getString("username", "");
        String password = sp.getString("password", "");
        this.username.setText(username);
        this.password.setText(password);
    }
}